//考试，计时逻辑
import {isEmpty} from '@/utils/index';
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex';
var timeMixin = {
	data(){
		return{
			startTime: 0, //总的开始答题时间
			currentStartTime: 0, //当前题目开始答题时间
			usedTime:0,
			timeTmp:"00:00:00"
		}
	},
	methods:{
		...mapMutations('homeworkStore',['updateSubjectDuration']),
		timer() {
			const {
				currentStartTime
			} = this;
			const curBaseTime = isEmpty(this.currentSubject.useDuration)?'0':this.currentSubject.useDuration;
			let duration = (new Date().getTime() - currentStartTime) / 1000 + parseInt(curBaseTime);
			duration = Math.round(duration);
			//转换成00:00:00
			let h = Math.floor(duration / 3600);
			let m = Math.floor((duration - h * 3600) / 60);
			let s = duration - h * 3600 - m * 60;
			h = this.toDouble(h)
			m = this.toDouble(m)
			s = this.toDouble(s)
			const time = h + ":" + m + ":" + s
			this.timeTmp = time
			// #ifdef APP-PLUS
			if (this.examDynamicsBar.isVisible()) {
				this.timeRender(this, time);
			}
			// #endif
		},
		reset() { //继续计时
			this.currentStartTime = new Date().getTime();
		},
		start() { //开始计时
			this.reset();
			this.time = setInterval(this.timer, 1000);
		},
		stop() { //暂停
			clearInterval(this.time);
		},
		//转换成2位数，前面补0
		toDouble(value) {
			return value < 10 ? "0" + value : "" + value;
		},
		timeRender: (context, text = '00:00:01') => {
			// #ifdef APP-PLUS
			const $this = context;
			const {
				top
			} = context.specs;
			const richtext = `<img src="/static/exam/examBar04.png" width="27px" height="20px"/>` +
				`<br/><font style="font-size:8px;">${text}</font>`;
			$this.examDynamicsBar.drawRichText(richtext, {
					top: '9px',
					left: '0px',
					width: '100%',
					height: '100%'
				}, {
					onClick: function(e) {}
				},
				'time'
			);
			// #endif
		},
		//单题用时，baseTime上次做题用时
		saveSingleTime() {
			const curBaseTime = isEmpty(this.currentSubject.useDuration)?'0':this.currentSubject.useDuration;
			const totalTimeS = Math.round((new Date().getTime() - this.currentStartTime) / 1000)+ parseInt(curBaseTime);
			this.updateSubjectDuration(totalTimeS);
			this.reset();
		},
		//总用时,totalBaseTime:上次做题总用时
		totalTime() {
			this.saveSingleTime() //保存最后一题的答题时间
			//以分为单位 保存做题时间
			let usedTime = (new Date().getTime() - this.startTime) / (60 * 1000);
			return usedTime.toFixed(2);
		},
		
	}
}
export default timeMixin;